package com.xsomnus.open.im.authv2.server.handler;

import com.xsomnus.open.im.protocol.request.LoginRequestPacket;
import com.xsomnus.open.im.protocol.response.LoginResponsePacket;
import com.xsomnus.open.im.util.PrintUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/25 0025 15:32
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {
    private final static Map<String, String> usernameMap;

    static {
        usernameMap = new HashMap<>(2 << 2);
        usernameMap.put("xsomnus666", "123456");
        usernameMap.put("jackson", "654321");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket msg) throws Exception {
        PrintUtils.print("收到客户端登陆请求");
        LoginResponsePacket responsePacket = new LoginResponsePacket();
        responsePacket.setVersion(msg.getVersion());
        if (validate(msg)) {
            responsePacket.setSuccess(true);
            System.out.println(new Date() + ": 登录成功!");
        } else {
            responsePacket.setReason("密码账号校验失败");
            responsePacket.setSuccess(false);
            PrintUtils.print("登陆失败");
        }
        ctx.channel().writeAndFlush(responsePacket);
    }

    private boolean validate(LoginRequestPacket loginRequestPacket) {
        return usernameMap.get(loginRequestPacket.getUsername()).equals(loginRequestPacket.getPassword());
    }

}
